package com.hjli.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.hjli.model.ArticleCommentInfo;
import com.hjli.model.ArticleInfo;
import com.hjli.model.TypeInfo;
import com.hjli.service.impl.ArticleService;
import com.hjli.service.impl.CommentService;
import com.hjli.service.impl.TagService;
import com.hjli.service.impl.TypeService;
import com.hjli.tool.EmailTool;
import com.hjli.tool.PropertiesTool;

@Controller
@RequestMapping("sys/article")
public class ArticleController {

	@Resource
	TagService tagService;
	@Resource
	TypeService typeService;
	@Resource
	ArticleService articleService;
	@Resource
	CommentService commentService;

	private int node = 0;

	/**
	 * 添加文章
	 * 
	 * @author Leo
	 * 
	 */
	@RequestMapping("create")
	public ModelAndView create() {
		ModelAndView model = new ModelAndView("admin/main/article/newArticle");
		List<TypeInfo> typeInfoList = typeService.typeInfoAll();
		model.addObject("typeList", typeInfoList);
		return model;
	}

	/**
	 * 修改页面显示
	 * 
	 * @author Leo
	 * 
	 */
	@RequestMapping("edit")
	public ModelAndView edit(@RequestParam(value = "articleId", required = false) int articleId) {
		ModelAndView model = new ModelAndView("admin/main/article/editArticle");
		//查询文章信息
		ArticleInfo article = articleService.selectByPrimaryKey(articleId);
		List<TypeInfo> typeInfoList = typeService.typeInfoAll();
		model.addObject("typeList", typeInfoList);
		model.addObject("article",article);
		return model;
	}
	
	/**
	 * 修改文章
	 * 
	 * @author Leo
	 * 
	 */
	@RequestMapping("update")
	public @ResponseBody Map<String, Object> update(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ArticleInfo articleInfo = new ArticleInfo();
		articleInfo.setId(Integer.parseInt(request.getParameter("id").toString()));
		
		if (request.getParameter("title") == null || request.getParameter("title").toString() == "") {
			resultMap.put("result", "文章标题不能为空！");
			return resultMap;
		}
		String aTitle = request.getParameter("title");// 标题
		articleInfo.setaTitle(aTitle);

		if (request.getParameter("type") == null || request.getParameter("type").toString() == "") {
			resultMap.put("result", "请选择文章类型！");
			return resultMap;
		}
		Integer aTypeid = Integer.parseInt(request.getParameter("type").toString());// 类型
		articleInfo.setaTypeid(aTypeid);

		if (request.getParameter("tags") == null || request.getParameter("tags").toString() == "") {
			resultMap.put("result", "请输入文章标签！");
			return resultMap;
		}
		String aTags = request.getParameter("tags").toString();// 标签
		articleInfo.setaTags(aTags);

		if (request.getParameter("md") == null || request.getParameter("md").toString() == "") {
			resultMap.put("result", "文章类容不能为空！");
			return resultMap;
		}
		String aContent = request.getParameter("md").toString();// 原文
		articleInfo.setaContent(aContent);
		if(articleService.updateByPrimaryKeySelective(articleInfo)==1){
			resultMap.put("result", "success");
		}else{
			resultMap.put("result", "更新失败");
		}
		return resultMap;

	}

	/**
	 * 保存文章
	 * 
	 * @author Leo
	 * 
	 */
	@RequestMapping("save")
	public @ResponseBody Map<String, Object> save(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ArticleInfo articleInfo = new ArticleInfo();
		if (request.getParameter("title") == null || request.getParameter("title").toString() == "") {
			resultMap.put("result", "文章标题不能为空！");
			return resultMap;
		}
		String aTitle = request.getParameter("title");// 标题
		articleInfo.setaTitle(aTitle);

//		String aDescripte = "-";// 描述(暂时留空字段)

		Date aDatetime = new Date();// 发布时间
		articleInfo.setaDatetime(aDatetime);

		if (request.getParameter("type") == null || request.getParameter("type").toString() == "") {
			resultMap.put("result", "请选择文章类型！");
			return resultMap;
		}
		Integer aTypeid = Integer.parseInt(request.getParameter("type").toString());// 类型
		articleInfo.setaTypeid(aTypeid);

		if (request.getParameter("tags") == null || request.getParameter("tags").toString() == "") {
			resultMap.put("result", "请输入文章标签！");
			return resultMap;
		}
		String aTags = request.getParameter("tags").toString();// 标签
		articleInfo.setaTags(aTags);

		if (request.getParameter("md") == null || request.getParameter("md").toString() == "") {
			resultMap.put("result", "文章类容不能为空！");
			return resultMap;
		}
		String aContent = request.getParameter("md").toString();// 原文
		articleInfo.setaContent(aContent);

		Integer aStar = 0;// 文章点赞数
		articleInfo.setaStar(aStar);

		Integer aState = 1;// 文章状态：1、已发布 2、草稿箱
		articleInfo.setaState(aState);

		Integer aViewnum = 0;// 文章浏览数
		articleInfo.setaViewnum(aViewnum);

		Integer aBelongid;// 文章发表人(暂时默认为0)
		articleInfo.setaBelongid(0);

		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String htmlName = sdf.format(aDatetime).toString() + ".html";
		
		articleInfo.setaUrl("html/" + htmlName);
		if (articleService.insert(articleInfo) == 1) {
			resultMap.put("result", "success");
		} else {
			resultMap.put("result", "保存失败");
		}
	
		return resultMap;
	}
	
	/**
	 * 删除文章
	 */
	@RequestMapping("delete")
	public @ResponseBody Map<String, Object> delete(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if(request.getParameter("id")!=null&&request.getParameter("id").toString()!=""){
			if(articleService.deleteByPrimaryKey(Integer.parseInt(request.getParameter("id").toString()))==1){
				resultMap.put("result", "success");
			}else{
				resultMap.put("result", "删除失败");
			}
		}
		return resultMap;
	}

	/**
	 * 文章列表
	 * 
	 * @author Leo
	 * @throws Exception
	 * 
	 */
	@RequestMapping("list")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView model = new ModelAndView("admin/main/article/listArticle");
		// List<ArticleInfo> articleInfoList = articleService.articleInfoAll();
		// model.addObject("list",articleInfoList);
		List<ArticleInfo> pageList = new ArrayList<ArticleInfo>();
		int nowPageNum;// 当前页数
		if (request.getParameter("nowPageNum") == null || request.getParameter("nowPageNum").toString() == "") {
			nowPageNum = 0;
		} else {
			nowPageNum = Integer.parseInt(request.getParameter("nowPageNum").toString());
		}
		Properties prop = PropertiesTool.getProperty("page.properties");

		int everyPageNum = Integer.parseInt(prop.getProperty("pageNum").toString());// 每页的数量
		int sumCount = articleService.sumPageNum();
		int sumPageNum;// 总页数
		if (sumCount > 0) {
			if (sumCount % everyPageNum == 0) {
				sumPageNum = sumCount / everyPageNum;
			} else {
				sumPageNum = sumCount / everyPageNum + 1;
			}
		} else {
			sumPageNum = 1;
		}

		// 获取到List<ArticleInfo> pageList;
		pageList = articleService.pageList(nowPageNum * everyPageNum, everyPageNum);

		model.addObject("sumPageNum", sumPageNum);
		model.addObject("list", pageList);
		return model;
	}

	/**
	 * 文章分页
	 * 
	 * @author Leo
	 */
	@RequestMapping("pageList")
	public @ResponseBody Map<String, Object> pageList(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<ArticleInfo> pageList = new ArrayList<ArticleInfo>();
		int nowPageNum;// 当前页数
		if (request.getParameter("nowPageNum") == null || request.getParameter("nowPageNum").toString() == "") {
			nowPageNum = 0;
		} else {
			nowPageNum = Integer.parseInt(request.getParameter("nowPageNum").toString());
		}
		int everyPageNum = Integer.parseInt(PropertiesTool.getValueByKey("page.properties", "pageNum").toString());// 每页的数量
		int sumCount = articleService.sumPageNum();
		int sumPageNum;// 总页数
		if (sumCount > 0) {
			if (sumCount % everyPageNum == 0) {
				sumPageNum = sumCount / everyPageNum;
			} else {
				sumPageNum = sumCount / everyPageNum + 1;
			}
		} else {
			sumPageNum = 1;
		}

		// 获取到List<ArticleInfo> pageList;
		pageList = articleService.pageList(nowPageNum * everyPageNum, everyPageNum);

		// 传入页面的值
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sumPageNum", sumPageNum);
		map.put("list", pageList);

		resultMap.put("result", map);

		return resultMap;
	}

	@RequestMapping("pictureUpload")  
    public @ResponseBody Map<String,Object> pictureUpload(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file, HttpServletRequest request) {  
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
        String realPath = request.getRealPath("/")+"assets/upload/";
        String fileName = file.getOriginalFilename();  
        File targetFile = new File(realPath, fileName);
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
        //保存  
        try {  
            file.transferTo(targetFile);  
            resultMap.put("success", 1);
            resultMap.put("message", "上传成功！");
            resultMap.put("url",request.getContextPath()+"/assets/upload/"+fileName);
        } catch (Exception e) {  
        	resultMap.put("success", 0);
            resultMap.put("message", "上传失败！");
            e.printStackTrace();  
        }  
        return resultMap;  
    }

}
